from socket import *
from datetime import datetime
import threading
import multiprocessing


log = open('log.txt', 'w+')

address = '0.0.0.0'
port = 50001
buffsize = 1024
s = socket(AF_INET, SOCK_STREAM)
s.bind((address, port))
s.listen(20)

days_dict = {}
d_list = {'S060291': [14, 41], 'S060296': [30, 42], 'S060298': [40, 32],
          'S000004': [46, 32], 'S000005': [46, 29], 'S060300': [55, 30]}


def logger(t):
    print(t, file=log)
    log.flush()


def tcplink(sock, addr):
    while True:
        try:
            recvdata = sock.recv(buffsize).decode('utf-8')
            if not recvdata:
                break
            if recvdata.endswith('\r\n'):
                logger('receive: ' + recvdata)
                d0 = recvdata[8:18]
                d = recvdata[0:7]
                if (d in d_list)and(d0!='0000000000') :
                    curr_day = datetime.now().strftime("%Y-%m-%d")
                    if curr_day not in days_dict:
                        days_dict[curr_day] = []
                    if d not in days_dict[curr_day]:
                        days_dict[curr_day].append(d)
                sock.sendall(b'\0')
        except Exception as e:
            sock.close()
            logger(f'{addr} offline')
            logger(e)
            break


def recs():
    while True:
        clientsock, clientaddress = s.accept()
        logger(f'connect from:{clientaddress}')
        t = threading.Thread(target=tcplink, args=(clientsock, clientaddress))
        t.start()


if __name__ == '__main__':
    t1 = threading.Thread(target=recs, args=(), name='rec')
    t1.start()
